package shaw.wifi;

import java.util.ArrayList;

import shaw.wifi.network.AsyncNetworkTask;
import shaw.wifi.network.ConnectionInformation;
import shaw.wifi.network.NetworkSettingsTask;
import shaw.wifi.nohttp.NetworkSettingsAESTask;
import shaw.wifi.nohttp.NetworkSettingsAuthTask;
import shaw.wifi.nohttp.NetworkSettingsEstablishConnectionTask;
import shaw.wifi.nohttp.NetworkSettingsGetNewAppInfoTask;
import shaw.wifi.nohttp.NetworkSettingsNoHttpTask;
import shaw.wifi.nohttp.SWEncrypt;
import android.content.Context;
import android.os.Build;
import android.util.Log;

public class NetworkSettingsTaskManager {
	private static NetworkSettingsTaskManager instance;	
	public static NetworkSettingsTaskManager get() {
		if(instance == null) {
			instance = new NetworkSettingsTaskManager();
		}
		return instance;
	}
	private NetworkSettingsTaskManager() {}
	
	private NetworkSettingsTaskRunner nstr = new NetworkSettingsTaskRunner();
	
	public NetworkSettingsTaskRunner getNSTR() {
		return nstr;
	}
	
	public void runTasks() {
		if(Build.VERSION.SDK_INT >= 0x0E /*Ice Cream Sandwich*/ && Constants._CANUSEHTTPS) {
			Log.e("RUN TASKS", "Running on fallback...");
			//use https with applicable versions (tested for ice cream sandwhich (android 4.0)
			Log.e("RUN TASKS", "Running https...");
			addNetworkSettingsTask(new NetworkSettingsTask());
		} else {
			//run fallback method
			addNetworkSettingsTask(new NetworkSettingsAuthTask());
			addNetworkSettingsTask(new NetworkSettingsEstablishConnectionTask());
			addNetworkSettingsTask(new NetworkSettingsGetNewAppInfoTask());
			addNetworkSettingsTask(new NetworkSettingsAESTask());
		}
		
		nstr.runNetworkSettingsTask();
	}
	
	//encryption information, should be refreshed with each session
	private SWEncrypt encryption = new SWEncrypt();
	public void refreshEncrypt() {
		encryption = new SWEncrypt();
	}
	
	private ArrayList<AsyncNetworkTask> taskList = new ArrayList<AsyncNetworkTask> ();
	public void addNetworkSettingsTask(AsyncNetworkTask t) {
		taskList.add(t);
		if(t instanceof NetworkSettingsNoHttpTask) {
			((NetworkSettingsNoHttpTask) t).setEncryptionObject(encryption);
		}
	}

	public void clearTasks() {
		taskList.clear();
	}

	public AsyncNetworkTask getNextTask() {
		if(taskList.size() > 0) {
			return taskList.get(0);
		}
		return null;
	}

	public void taskComplete() {
		if(taskList.size() > 0) {
			taskList.remove(0);
		}
	}
	
	private Context ctx;
	public Context getApplicationContext() {
		return ctx;
	}
	public void setApplicationContext(Context ctx) {
		this.ctx = ctx;
	}
	public ConnectionInformation getConnInfo() {
		return nstr.getConnInfo();
	}
}
